package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.cache.util.RedisKeys;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyComment;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.query.StrategyCommentQuery;
import cn.wolfcode.wolf2w.repository.StrategyCommentRepository;
import cn.wolfcode.wolf2w.service.IStrategyCommentService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.util.DBHelper;
import cn.wolfcode.wolf2w.util.DateUtil;
import cn.wolfcode.wolf2w.vo.StrategyStatisVO;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 攻略评论服务接口实现
 */
@Service
//@Transactional  现在写不能事务, 需要讲完复制集才能使用事务
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private StrategyCommentRepository repsitory;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IStrategyService strategyService;


    @Override
    public void save(StrategyComment strategyComment) {
        strategyComment.setId(null);
        strategyComment.setCreateTime(new Date());
        StrategyStatisVO vo = this.getStrategyVo(strategyComment.getStrategyId());
        vo.setReplynum(vo.getReplynum() + 1);
        this.setStrategyVo(vo, strategyComment.getStrategyId());
        repsitory.save(strategyComment);
    }

    @Override
    public void update(StrategyComment strategyComment) {
        repsitory.save(strategyComment);
    }

    @Override
    public void delete(String id) {
        repsitory.deleteById(id);
    }

    @Override
    public StrategyComment get(String id) {
        return repsitory.findById(id).orElse(null);
    }

    @Override
    public List<StrategyComment> list() {
        return repsitory.findAll();
    }

    @Override
    public Page<StrategyComment> query(StrategyCommentQuery qo) {
        Query query = new Query();
        query.addCriteria(Criteria.where("strategyId").is(qo.getStrategyId()));
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "createTime");
        return DBHelper.query(template, query, qo, StrategyComment.class, pageable);
    }

    @Override
    public void saveOrUpdate(StrategyComment strategyComment) {
        if (StringUtils.hasLength(strategyComment.getId())) {
            //update
            this.update(strategyComment);
        } else {
            //save
            this.save(strategyComment);
        }
    }

    @Override
    public void commentThumb(String cid, String sid, UserInfo user) {
        StrategyComment strategyComment = this.get(cid);
        List<String> thumbuplist = strategyComment.getThumbuplist();
        if (thumbuplist.contains(user.getId())) {
            strategyComment.setThumbupnum(strategyComment.getThumbupnum() - 1);
            thumbuplist.remove(user.getId());
            strategyComment.setThumbuplist(thumbuplist);

        } else {
            strategyComment.setThumbupnum(strategyComment.getThumbupnum() + 1);
            strategyComment.getThumbuplist().add(user.getId());
        }
        this.update(strategyComment);
    }


    @Override
    public StrategyStatisVO statisVo(String sid, int num) {
        StrategyStatisVO vo = this.getStrategyVo(sid);
        vo.setViewnum(vo.getViewnum() + num);
        this.setStrategyVo(vo, sid);
        return vo;
    }

    public StrategyStatisVO getStrategyVo(String sid) {
        String voKey = RedisKeys.STRATEGY_STATIS_VO.join(sid);
        StrategyStatisVO vo = null;
        if (redisTemplate.hasKey(voKey)) {
            String strategyVostr = redisTemplate.opsForValue().get(voKey);
            vo = JSON.parseObject(strategyVostr, StrategyStatisVO.class);
        } else {
            Strategy strategy = strategyService.get(sid);
            vo = new StrategyStatisVO();
            BeanUtils.copyProperties(strategy, vo);
            vo.setStrategyId(strategy.getId());
        }
        return vo;
    }

    public void setStrategyVo(StrategyStatisVO vo, String sid) {
        String voKey = RedisKeys.STRATEGY_STATIS_VO.join(sid);
        redisTemplate.opsForValue().set(voKey, JSON.toJSONString(vo));
    }

    @Override
    public boolean favor(String sid, String uid) {
        String uidKey = RedisKeys.USER_FAVOR.join(uid);
        StrategyStatisVO vo = this.getStrategyVo(sid);
        List<String> uidList = null;
        if (redisTemplate.hasKey(uidKey)) {
            String uidListStr = redisTemplate.opsForValue().get(uidKey);
            uidList = JSON.parseArray(uidListStr, String.class);
        } else {
            uidList = new ArrayList<>();
        }
        if (uidList.contains(sid)){
            uidList.remove(sid);
            vo.setFavornum(vo.getFavornum()-1);
        }else {
            uidList.add(sid);
            vo.setFavornum(vo.getFavornum()+1);
        }
        redisTemplate.opsForValue().set(uidKey, JSON.toJSONString(uidList));
        this.setStrategyVo(vo, sid);
        return uidList.contains(sid);
    }

    @Override
    public boolean strategyThumbup(String sid, String uid) {
        Date now = new Date();
        Date end = DateUtil.getEndDate(now);
        long time = DateUtil.getDateBetween(end, now);
        String thumbKey = RedisKeys.STRATEGY_THUMB.join(uid, sid);
        StrategyStatisVO vo = this.getStrategyVo(sid);
        if (redisTemplate.hasKey(thumbKey)){
            return false;
        }else {
            vo.setThumbsupnum(vo.getThumbsupnum()+1);
            redisTemplate.opsForValue().set(thumbKey, "1",time,TimeUnit.SECONDS);
            this.setStrategyVo(vo, sid);
        }
        return true;
    }
}
